/************************************
 * Package: RGcpp					*
 * Authors: Rui Eduardo Gouveia Gil	*
 * Date: 2010						*
 ************************************/
#include "rgcpp/exceptions/RuntimeException.h"
#include "rgcpp/sys/SysCommand.h"
#ifndef _WIN32
namespace rgcpp
{

SysCommand::SysCommand(const std::string& command)
{
	this->command = command;
	this->file = popen(command.c_str(),"r");

	if(!this->file)
	{
		Throw(SystemException(std::string("Unable to invoke command: ")+strerror(errno)));
	}
}

SysCommand::~SysCommand()
{
	if(this->file)
		pclose(this->file);
}

std::string SysCommand::readLine()
{
	if(fgets(this->buffer,2048,this->file))
	{
		std::string line(this->buffer);
		if(!line.empty())
			return line;
	}

	return "";
}

std::string SysCommand::cancel()
{
	pclose(this->file);
	this->file = NULL;
}

int SysCommand::invoke(const std::string& command)
{
	return system(command.c_str());
}

int SysCommand::invoke(const std::string& command, const char *fmt, ...)
{
	char buffer[1024];

	va_list vaList;
	va_start(vaList,fmt);
	vsnprintf(buffer,1024,fmt,vaList);
	va_end(vaList);

	std::string _command = command;
	_command += " ";
	_command += std::string(buffer);

	return system(_command.c_str());
}

std::vector<std::string> SysCommand::invokeWithReturn(const std::string& command)
{
	char buffer[1024];
	std::vector<std::string> result;
	FILE* file = popen(command.c_str(),"r");

	if(!file)
	{
		Throw(SystemException(std::string("Unable to invoke command: ")+strerror(errno)));
	}

	while(fgets(buffer,1024,file))
	{
		std::string line(buffer);
		result.push_back(line);
	}

	pclose(file);

	return result;
}

std::vector<std::string> SysCommand::invokeWithReturn(const std::string& command, const char *fmt, ...)
{
	char buffer[1024];
	std::vector<std::string> result;

	va_list vaList;
	va_start(vaList,fmt);
	vsnprintf(buffer,1024,fmt,vaList);
	va_end(vaList);

	std::string _command = command;
	_command += " ";
	_command += std::string(buffer);

	FILE* file = popen(_command.c_str(),"r");

	if(!file)
	{
		Throw(SystemException(std::string("Unable to invoke command: ")+strerror(errno)));
	}

	while(fgets(buffer,1024,file))
	{
		std::string line(buffer);
		boost::trim(line);
		result.push_back(line);
	}

	pclose(file);

	return result;
}

}
#endif